<?php
/**
 * @version $Id: language.php 1238 2010-06-07 02:45:52Z elkuku $
 * @package    EasyCreator
 * @subpackage Helpers
 * @author     EasyJoomla {@link http://www.easy-joomla.org Easy-Joomla.org}
 * @author     Nikolai Plath (elkuku) {@link http://www.nik-it.de NiK-IT.de}
 * @author     Created on 25-May-2008
 * @license    GNU/GPL, see JROOT/LICENSE.php
 */

//-- No direct access
defined('_JEXEC') or die('=;)');

/**
 * EasyLanguage helper class
 *
 * @package    EasyCreator
 * @subpackage Helpers
 *
 */
class EasyLanguage
{
    private $_languages = '';
    private $_fileList = array();
    private $_com_name = '';
    private $_default_lang = 'en-GB';

    private $_strings = array();
    private $_default_file = array();

    /**
     *  definitions found in php and xml files
     */
    private $_definitions = array();

    private $_showCore = '';
    private $_coreStrings = array();

    /*
     * scope for translation admin/site/menu
     */
    private $_scope = '';

    /*
     * languages to hide
     */
    private $_hideLangs;

    private $project = null;


    /**
     * Constructor.
     * @param EasyProject $project
     * @param string $scope
     * @param array $hideLangs
     */
    public function __construct(EasyProject $project, $scope, $hideLangs)
    {
        $this->_hideLangs = $hideLangs;
        $this->_com_name = $project->comName;
        $this->_languages = $this->setLangs($project->langs);

        $this->project = $project;
        $this->_scope = $scope;
        $this->_showCore = JRequest::getVar('showCore');

        if($scope == 'menu')
        {
            $this->readMenu();
        }
        else
        {
            $this->_fileList = $this->_buildFileList($project->copies, $scope);
        }
    }//function

    /**
     * sets the languages.
     * ensures that en-GB is always in first place.
     *
     * @param array $languages
     * @return array
     */
    private function setLangs($languages)
    {
        if( ! is_array($languages))
        {
            return array();
        }

        if( ! array_key_exists('en-GB', $languages))
        {
            JError::raiseWarning(100, 'Default language en-GB is not present');
            return array();
        }

        //--assure that default 'en-GB' is in first place
        $result = array('en-GB');

        foreach ($languages as $key => $scopes)
        {
            if($key != 'en-GB')
            {
                $result[] = $key;
            }
        }//foreach

        return $result;
    }//function

    /**
     *
     * @param unknown_type $lang
     * @param unknown_type $key
     */
    public function getTranslation($lang, $key)
    {
        $path =($this->_scope == 'admin' || $this->_scope == 'menu') ? JPATH_ADMINISTRATOR : JPATH_SITE;
        $this->_readStrings($path);

        $translation =(isset($this->_strings[$key][$lang])) ? $this->_strings[$key][$lang] : '';
        return $translation;
    }//function

    /**
     * gets the saved versions.
     *
     * @param string $lang
     * @return array(object) array of versions
     */
    public function getVersions($lang)
    {
        $versions = array();
        $fileName = $this->getFileName($lang, $this->_scope, $this->project);
        if( ! JFile::exists($fileName))
        {
            JError::raiseWarning(100, JText::sprintf('The file %s could not be found', $fileName));
            return $versions;
        }

        $r = 1;
        while($r > 0)
        {
            $test = '.r'.$r;
            if(JFile::exists($fileName.$test))
            {
                $version = new JObject();
                $lastMod = date ("d-M-y H:i.", filectime($fileName.$test));

                $size = $this->byte_convert(filesize($fileName.$test));
                $version->fileName = JFile::getName($fileName.$test);
                $version->revNo = substr(JFile::getExt($test),1);
                $version->lastMod = $lastMod;
                $version->size = $size;

                $versions[] = $version;
                $r++;
            }
            else
            {
                $r = 0;
            }
        }//while

        return $versions;
    }//function

    public function getLanguages()
    {
        return $this->_languages;
    }//function

    public function getHideLangs()
    {
        return $this->_hideLangs;
    }//function

    public function getDefinitions()
    {
        return $this->_definitions;
    }//function

    public function getStrings()
    {
        return $this->_strings;
    }//function

    public function getCoreStrings()
    {
        return $this->_coreStrings;
    }//function

    public function getDefaultFile()
    {
        return $this->_default_file;
    }//function

    /**
     * displays the actual file and a selected version side by side
     *
     * @param int $revNo
     * @param string $lang
     */
    public function displayVersion($revNo, $lang)
    {
        $fileName = $this->getFileName($lang, $this->_scope, $this->project);
        $sRev = '.r'.$revNo;

        $fileNameOrig = $fileName;
        $fileNameRev = $fileName.'.r'.$revNo;

        $fileOrig = '';
        $fileRev = '';

        if(JFile::exists($fileNameOrig))
        {
            $fileOrig = JFile::read($fileNameOrig);
            if($fileOrig)
            {
                $fileOrig = explode("\n", $fileOrig);
            }
        }
        if(JFile::exists($fileNameRev))
        {
            $fileRev = JFile::read($fileNameRev);
            if($fileRev)
            {
                $fileRev = explode("\n", $fileRev);
            }
        }

        ecrLoadHelper('DifferenceEngine');

        //--we are adding a blank line to the end.. this is somewhat 'required' by PHPdiff
        if($fileOrig[count($fileOrig)-1] != '')
        {
            $fileOrig[] = '';
        }
        if($fileRev[count($fileRev)-1] != '')
        {
            $fileRev[] = '';
        }

        $dwDiff = new Diff($fileRev, $fileOrig);
        $dwFormatter = new TableDiffFormatter();

        ?>

<table class="diff">
	<tr>
		<th colspan="2"><?php echo JText::sprintf('Version No. %s', $revNo); ?></th>
		<th colspan="2"><?php echo JText::_('Actual file'); ?></th>
	</tr>
	<?php echo $dwFormatter->format($dwDiff); ?>
</table>
	<?php

	/* PHP */

	?>
<!--
		<table width="100%">
			<tr>
				<th><?php echo JText::_('Actual file'); ?></th>
				<th><?php echo JText::sprintf('Version No. %s', $revNo); ?></th>
			</tr>
			<tr valign="top">
			<?php

			?>
				<td><?php if( ! $fileOrig)
				{
					echo '<strong style="color: red;">'.JText::_('File not found').'</strong>';
				}
				else
				{
					$this->displayFields($lang, $fileOrig);
				}
				?></td>
				<td><?php if( ! $fileRev)
				{
					echo '<strong style="color: red;">'.JText::_('File not found').'</strong>';
				}
				else
				{
					$this->displayFields($lang, $fileRev);
				}
				?></td>
			</tr>
		</table>
		-->
				<?php
    }//function

    private function byte_convert($bytes)
    {
        $symbol = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB');

        $exp = 0;
        $converted_value = 0;
        if($bytes > 0)
        {
            $exp = floor(log($bytes)/log(1024));
            $converted_value = ($bytes/pow(1024,floor($exp)));
        }

        return sprintf('%.2f '.$symbol[$exp], $converted_value);
    }//function

    function correctTranslation($defaultLanguage, $translatedLanguage)
    {
        $correctedLanguage = array();

        //--read the header from translated language
        foreach($translatedLanguage as $line)
        {
            $corrected = new JObject();
            if($line->key == '#')
            {
                $corrected->key = '#';
                $corrected->value = $line->value;
                $correctedLanguage[] = $corrected;
            }
            else
            {
                break;
            }
        }//foreach

        $isHeader = true;
        foreach($defaultLanguage as $line)
        {
            $corrected = new JObject();
            if($line->key == '#')
            {
                if( ! $isHeader)
                {
                    $corrected->key = '#';
                    $corrected->value = $line->value;
                    $correctedLanguage[] = $corrected;
                }
            }
            else
            {
                $isHeader = false;
                $trans = '**TRANSLATE**';
                foreach ($translatedLanguage as $tLine)
                {
                    if($tLine->key == $line->key)
                    {
                        $trans = $tLine->value;
                        break;
                    }
                }//foreach
                $corrected->key = $line->key;
                $corrected->value = $trans;
                $correctedLanguage[] = $corrected;
            }
        }//foreach

        return $correctedLanguage;
    }//function

    function saveFile($lang, $fileContents)
    {
        ecrLoadHelper('file');

        $fileName = $this->getFileName($lang, $this->_scope, $this->project);

        //--Save a version ?
        $saveVersion = JRequest::getInt('save_version', '1');
        if($saveVersion)
        {
            if( ! EasyFile::saveVersion($fileName))
            {
                return false;
            }
        }

        $fileContents = implode("\n", $fileContents);
        if ( ! JFile::write($fileName, $fileContents))
        {
            JError::raiseWarning(100,JText::_('Unable to write file').$fileName);
            return false;
        }
        JError::raiseNotice(100, JText::_('The file has been saved'));

        return true;
    }//function

    function saveTranslation($lang, $key, $translation, $position = 0)
    {
        ecrLoadHelper('file');

        $fileName = $this->getFileName($lang, $this->_scope, $this->project);

        $origFile = $this->parseFile($fileName);
        $resultFile = array();
        $pos = 1;
        $found = false;

        foreach ($origFile as $line)
        {
            switch($line->key)
            {
                case '#':
                case '-':
                    $resultFile[] = $line->value;
                    $pos ++;
                    break;
                default:
                    if($line->key == $key)
                    {
                        //--Found it
                        $resultFile[] = $line->key.'='.$translation;
                        $pos ++;
                        $found = true;
                    }
                    else
                    {
                        $resultFile[] = $line->key.'='.$line->value;
                    }
                    break;
            }//switch
        }//foreach

        if( ! $found)
        {
            //--New translation - append
            $resultFile[] = $key.'='.$translation;
        }

        $fileContents = implode("\n", $resultFile);

        //--Save a version ?
//        $saveVersion = JRequest::getInt('save_version', '1');
//
//        if($saveVersion)
//        {
            if( ! EasyFile::saveVersion($fileName))
            {
                return false;
            }
//        }

        if ( ! JFile::write($fileName, $fileContents))
        {
            JError::raiseWarning(100, JText::_('Unable to write file').$fileName);
            return false;
        }

        return true;
    }//function

    function deleteTranslation($lang, $key)
    {
        ecrLoadHelper('file');

        $fileName = $this->getFileName($lang, $this->_scope, $this->project);

        $origFile = $this->parseFile($fileName);
        $resultFile = array();
        $pos = 1;
        $found = false;

        foreach ($origFile as $line)
        {
            switch($line->key)
            {
                case '#':
                case '-':
                    $resultFile[] = $line->value;
                    $pos ++;
                    break;
                default:
                    if($line->key == $key)
                    {
                        //--Found it
                        $found = true;
                    }
                    else
                    {
                        $resultFile[] = $line->key.'='.$line->value;
                    }
                    break;
            }//switch
        }//foreach

        if( ! $found)
        {
            //--New translation - append
            JError::raiseWarning(100, JText::_('Key not found').' : '.$key);
            return false;
        }

        $fileContents = implode("\n", $resultFile);

        //--Save a version ?
        $saveVersion = JRequest::getInt('save_version', '1');

        if($saveVersion)
        {
            if( ! EasyFile::saveVersion($fileName))
            {
                return false;
            }
        }

        if ( ! JFile::write($fileName, $fileContents))
        {
            JError::raiseWarning(100, JText::_('Unable to write file').$fileName);

            return false;
        }

        return true;
    }//function

    /**
     * reads the strings from language files
     *
     * @param string $path
     */
    function _readStrings($path, $core = false)
    {
        foreach ($this->_languages as $lang)
        {
            if(in_array($lang, $this->_hideLangs))
            {
                continue;
            }

            //--Read the file
            $file = $this->_getFile($lang, $path, $core);

            if( ! $file)
            {
                continue;
            }

            foreach($file as $line)
            {
                $line = trim($line);
                if(strpos($line, '#') === 0)
                {
                    //--Comment line
                    if($core)
                    {
                        //--Don't care about core comments ;)
                        continue;
                    }

                    if(strpos($line, '@version'))
                    {
                        //--Version string found
                        if($lang == $this->_default_lang)
                        {
                            $this->_default_file[] = array('version'=>$line);
                        }

                        continue;
                    }

                    if($lang == $this->_default_lang)
                    {
                        $this->_default_file[] = array('comment'=>$line);
                    }

                    continue;
                }

                $eqpos = strpos($line, '=');

                if($eqpos)
                {
                    //--Found a pair
                    $key = substr($line, 0, $eqpos);
                    $value = substr($line, $eqpos + 1);
                    if( ! array_key_exists($key, $this->_strings) && ! $core)
                    {
                        $this->_default_file[] = array('key' => array($key => $value));
                    }

                    if($core)
                    {
                        $this->_coreStrings[$key][$lang] = $value;
                    }
                    else
                    {
                        $this->_strings[$key][$lang] = $value;
                    }

                    continue;
                }

                if($lang == $this->_default_lang && ! $core)
                {
                    $this->_default_file[] = array('etc' => $line);
                }
            }//foreach
        }//foreach

    }//function

    function parseFile($path)
    {
        if( ! JFile::exists($path))
        {
            JError::raiseWarning(100,JText::sprintf('File %s not found', $path));
            return false;
        }

        //--Read the file
        $file = explode("\n", JFile::read($path));
        $parsed = array();

        foreach($file as $line)
        {
            $line = trim($line);
            $translation = new stdClass();

            if(strpos($line, '#') === 0)
            {
                //--Comment line
                $translation->key = '#';
                $translation->value = $line;
                $parsed[]=$translation;

                continue;
            }

            $eqpos = strpos($line, '=');

            if($eqpos)
            {
                //--Found a pair
                $key = substr($line, 0, $eqpos);
                $value = substr($line, $eqpos + 1);
                $translation->key = $key;
                $translation->value = $value;
                $parsed[]=$translation;

                continue;
            }

            $translation->key = '-';
            $translation->value = $line;

            $parsed[]=$translation;
        }//foreach

        return $parsed;
    }//function

    private function drawTableLanguageFiles($path)
    {
        $lang_first_line_comment = 3;
        $lang_first_line_comment_cnt = 0;
        $tableHeader = '';
        $tableHeader .= NL.'<table class="adminlist">';
        $tableHeader .= NL.'<thead>';
        $tableHeader .= '<tr>';
        $tableHeader .= '<th style="background-color: #CCE5FF;">'.JText::_('KEY').'</th>';
        foreach ($this->_languages as $lang)
        {
            if(in_array($lang, $this->_hideLangs))
            {
                continue;
            }
            $tableHeader .= '<th width="'.(100 / (count($this->_languages) + 2)).'%">'.$lang.'</th>';
        }//foreach
        $tableHeader .= '<th style="background-color: #FFFFB2;">'.JText::_('Used in File').'</th>';
        $tableHeader .= '</tr>';
        $tableHeader .= '</thead>'.NL;
        $sliderDrawed = false;
        $started = false;

        $lang_fileanalysis_fold = JRequest::getVar('lang_fileanalysis_fold', '');
        $lang_fileanalysis_comment_num = JRequest::getInt('lang_fileanalysis_comment_num', 0);
        $lang_fileanalysis_active = JRequest::getInt('lang_fileanalysis_active', 0);

        $checked =($lang_fileanalysis_fold) ? ' checked="checked"' : '';

        if($checked)
        {
            jimport('joomla.html.pane');
        }
        ?>
<table>
	<tr>
		<td>
		<h2><?php echo JText::_('Language files analysis'); ?></h2>
		</td>
		<td><?php echo JText::_('Treat the first')?> <select
			name="lang_fileanalysis_comment_num"
			onchange="submitbutton('languages');">
			<?php
			for($i = 0; $i<10; $i++)
			{
			    $selected =($lang_fileanalysis_comment_num == $i) ? ' selected="selected"' : '';
			    echo '<option'.$selected.'>'.$i.'</option>';
			}//for
			?>
		</select> <?php echo JText::_('lines as comment')?> <br />
		<input type="checkbox" name="lang_fileanalysis_fold"
			id="lang_fileanalysis_fold" value="lang_fileanalysis_fold"
			onclick="submitbutton('languages');" <?php echo $checked; ?>> <label
			for="lang_fileanalysis_fold"><?php echo JText::_('Fold'); ?></label>
		</td>
	</tr>
</table>
			<?php
			$k = 0;
			$folder_num = -1;
			$fieldID = 0;
			$ecr_project = JRequest::getCmd('ecr_project');
			foreach ($this->_default_file as $line)
			{
			    foreach ($line as $key=>$value)
			    {
			        switch($key)
			        {
			            case 'comment':
			                if($lang_first_line_comment_cnt < $lang_fileanalysis_comment_num)
			                {
			                    echo $value.'<br />';
			                    $lang_first_line_comment_cnt ++;
			                }
			                else
			                {
			                    if($lang_fileanalysis_fold)
			                    {
			                        $value = substr($value, 1);
			                        if($sliderDrawed)
			                        {
			                            echo '</table>';
			                            echo $pane2->endPanel();
			                            echo $pane2->startPanel($value,  $value.'-ini-analysis-page');
			                            echo $tableHeader;
			                        }
			                        else
			                        {
			                            $pane2 =& JPane::getInstance('sliders', array('startOffset'=>$lang_fileanalysis_active, 'startTransition'=>''));
			                            echo $pane2->startPane($path.'-pane');
			                            echo $pane2->startPanel($value,  $value.'-analysis-page');
			                            echo $tableHeader;
			                            $sliderDrawed = true;
			                        }
			                        $k = 0;
			                        $folder_num ++;
			                    }
			                    else
			                    {
			                        if( ! $started)
			                        {
			                            echo $tableHeader;
			                            $started = true;
			                        }
			                        echo NL.'<tr>';
			                        echo '<td colspan="'.(count($this->_languages) + 2).'" style="background-color: #FFE5B2;">'.$value.'</td>';
			                        echo '</tr>';
			                    }
			                }
			                break;

			            case 'key':
			                $lang_first_line_comment_cnt = $lang_fileanalysis_comment_num;
			                if( ! $sliderDrawed && ! $started)
			                {
			                    echo $tableHeader;
			                    $started = true;
			                }
			                echo NL.'<tr class="row'.$k.'">';
			                foreach ($value as $skey=>$svalue)
			                {
			                    echo '<td align="left"><span style="color: #666666;">'.$skey.'</span></td>';

			                    foreach($this->_languages as $lang)
			                    {
			                        if(in_array($lang, $this->_hideLangs))
			                        {
			                            continue;
			                        }
			                        echo '<td>';
			                        $fieldID ++;
			                        $link = 'index.php?option=com_easycreator&amp;task=translate&amp;tmpl=component&amp;view=languages&amp;controller=languages';
			                        $link .= '&amp;ecr_project='.$ecr_project;
			                        $link .= '&amp;trans_lang='.$lang;
			                        $link .= '&amp;trans_key='.$skey;
			                        $link .= '&amp;field_id='.$fieldID;

			                        JHTML::_('behavior.modal', 'a.modal');
			                        ?>

<a class="modal" title="<?php echo JText::_('Click to translate'); ?>"
	href="<?php echo $link; ?>"
	rel="{handler: 'iframe', size: {x: 900, y: 310}}"
	id="trfield_<?php echo $fieldID; ?>"> <?php
	$tmpStrings =(isset($this->_strings[$skey][$lang])) ? $this->_strings[$skey][$lang] : array();
	$this->_displayField($lang, $skey, $tmpStrings);
	?> </a>
	<?php
	echo '</td>';
			                    }//foreach
			                    $used = false;
			                    echo '<td>';
			                    foreach ($this->_definitions as $definition)
			                    {
			                        if($skey == strtoupper($definition->definition))
			                        {
			                            foreach($this->_languages as $lang)
			                            {
			                                if(in_array($lang, $this->_hideLangs))
			                                {
			                                    continue;
			                                }
			                                if(isset($this->_strings[$skey][$lang]) && $this->_strings[$skey][$lang])
			                                {
			                                    $definition->translated[] = $lang;
			                                }
			                                if(isset($this->_coreStrings[$skey][$lang]) && $this->_coreStrings[$skey][$lang])
			                                {
			                                    $definition->coreTranslated[] = $lang;
			                                }
			                            }//foreach
			                            foreach($definition->files as $fName=>$fCount)
			                            {
			                                if($this->_scope == 'menu')
			                                {
			                                    echo '<span style="background-color: #FFFFB2;">'.$fCount.'</span><br />';
			                                }
			                                else
			                                {
			                                    echo '<span style="background-color: #FFFFB2;">'.JFile::getName($fName).'('.$fCount.') (<strong class="hasEasyTip" style="color:blue;" title="'.$fName.'">aaaXXW'.JText::_('PATH').'</strong>)</span><br />';
			                                }
			                            }//foreach
			                            $used = true;
			                        }
			                    }//foreach

			                    if( ! $used)
			                    {
			                        echo '<strong style="color: red;">'.JText::_('NOT USED').'</strong>';
			                    }
			                }//foreach
			                echo '</td>';
			                echo '</tr>';
			                break;

                        case 'version':
                        case 'etc':

                            break;
			        }//switch
			        $k = 1- $k;
			    }//foreach

			}//foreach
			echo '</table>';
			if($sliderDrawed)
			{
			    echo $pane2->endPanel();
			    echo $pane2->endPane();
			}
    }//function

    private function _showFiles($path)
    {
        ?>
<table>
	<tr valign="top">
	<?php
	foreach ($this->_languages as $lang)
	{
	    if(in_array($lang, $this->_hideLangs))
	    {
	        continue;
	    }
	    ?>
		<td><?php
		echo $lang.'<br />';

		//--read the file
		$file = $this->_getFile($lang, $path);
		if($file)
		{
		    $this->displayFields($lang, $file);
		    $this->displayRaw($file);
		}
		else
		{
		    echo '<p style="color: red">'.JText::_('File not found').'</p>';
		    ?>
		<div class="ecr_button"
			onclick="document.adminForm.lngcreate_lang.value='<?php echo $lang; ?>'; submitform('create_langfile');">
			<?php echo JText::_('Create language file'); ?></div>
			<?php
		}
		?></td>
		<?php
	}//foreach
	?>
	</tr>
</table>
	<?php
    }//function

    private function readMenu()
    {
        if(isset($this->project->menu['text']) && $this->project->menu['text'])
        {
            $text = str_replace('com_', '', $this->project->comName);
            $text = $this->project->comName;
            $this->_addDefinition($text, 'menu');
        }
        if(isset($this->project->submenu) && count($this->project->submenu))
        {
            foreach ($this->project->submenu as $subMenu)
            {
                $text = $this->project->comName.'.'.$subMenu['text'];
                $this->_addDefinition($text, 'submenu');
            }//foreach
        }
    }//function

    /**
     * Build a list of files to search for translation strings
     *
     * @param $copys array folders and files
     * @param $scope string admin/site/menu
     * @return void
     */
    function _buildFileList($copys, $scope)
    {
        foreach ($copys as $copyItem)
        {
            if($scope == 'admin')
            {
                //--admin scope - only load files from folders starting with 'admin'
                if($this->project->type != 'plugin'
                && strpos($copyItem, JPATH_ADMINISTRATOR) === false)
                {
                    continue;
                }
            }
            else
            {
                //--site scope - only load files from folders NOT starting with 'admin'
                if(strpos($copyItem, JPATH_ADMINISTRATOR) === 0)
                #				if(substr($copyItem['source'], 0, 5) == 'admin')
                {
                    continue;
                }
            }
            if(JFolder::exists($copyItem))
            {
                //--Add all PHP and XML files from a given folder
                $files = JFolder::files($copyItem, '\.php$|\.xml$', true, true);
                #$files = JFolder::files($copyItem, '\.xml$', true, true);
                $this->_fileList = array_merge($this->_fileList, $files);
            }
            else if(JFile::exists($copyItem))
            {
                //--Add a single file
                if( ! in_array($copyItem, $this->_fileList))
                {
                    $this->_fileList[] = $copyItem;
                }
            }
        }//foreach

        $manifest = EasyProjectHelper::findManifest($this->project);

        if($manifest && ! in_array(JPATH_ROOT.DS.$manifest, $this->_fileList))
        {
            $this->_fileList[] = JPATH_ROOT.DS.$manifest;
        }

        if ( ! count($this->_fileList))
        {
            return;
        }

        foreach($this->_fileList as $fileName)
        {
            $definitions = $this->getKeys($fileName);

            foreach($definitions as $definition => $fileName)
            {
                $this->_addDefinition($definition, $fileName);;
            }//foreach
        }//foreach

    }//function

    /**
     * Get JText Keys from a given file.
     *
     * @param string $fileName
     *
     * @return array keys as key, file names as value
     */
    public static function getKeys($fileName)
    {
        $definitions = array();

        //--RegEx pattern for JText
        $pattern = "/JText::_\(\s*\'(.*)\'\s*\)|JText::_\(\s*\"(.*)\"\s*\)".
		    "|JText::sprintf\(\s*\"(.*)\"|JText::sprintf\(\s*\'(.*)\'".
		    "|JText::printf\(\s*\'(.*)\'|JText::printf\(\s*\"(.*)\"/iU";

        switch(JFile::getExt($fileName))
        {
            case 'php':
                //--Search PHP files
                $contents = JFile::read($fileName);

                preg_match_all($pattern, $contents, $matches, PREG_SET_ORDER);

                foreach($matches as $match)
                {
                    foreach($match as $key=> $m)
                    {
                        $m = ltrim($m);
                        $m = rtrim($m);
                        if ($m == ''|| $key == 0) continue;

                        $definitions[$m] = $fileName;
                    }//foreach
                }//foreach
                break;
            case 'xml':
                //--Search XML files
                if ($xmlDoc = EasyProjectHelper::getXML($fileName))
                {
                    if((string)$xmlDoc->description)
                    {
                        $definitions[(string)$xmlDoc->description] = $fileName;
                    }

                    foreach($xmlDoc->params as $params)
                    {
                        $s = (string)$params->attributes()->group;

                        if($s) $definitions[$s] = $fileName;

                        foreach($params->param as $param)
                        {
                            $s = (string)$param->attributes()->label;

                            if($s) $definitions[$s] = $fileName;

                            $s = (string)$param->attributes()->default;

                            if($s != (int)($s))
                            {
                                //-- Don't add numbers
                                if($s) $definitions[$s] = $fileName;
                            }

                            $s = (string)$param->attributes()->description;

                            if($s) $definitions[$s] = $fileName;

                            foreach($param->option as $option)
                            {
                                $s = (string)$option;

                                if($s) $definitions[$s] = $fileName;
                            }//foreach
                        }//foreach
                    }//foreach
                }
                break;
        }//switch

        return $definitions;
    }//function

    function _addDefinition($definition, $file)
    {
        $def = new stdClass();
        $def->definition = $definition;
        $def->translated = array();
        $def->coreTranslated = array();

        if( ! count($this->_definitions))
        {
            if($file != 'menu' && $file != 'submenu')
            {
                $def->files = array(substr($file, strlen(JPATH_ROOT))=>1);
            }
            else
            {
                $def->files = array($file);
            }
            $this->_definitions[] = $def;
        } else
        {
            $exists = false;
            foreach ($this->_definitions as $a_def)
            {
                if($a_def->definition == $def->definition)
                {
                    $exists = true;
                    if(array_key_exists(substr($file, strlen(JPATH_ROOT)), $a_def->files))
                    {
                        //-- definition exists - increase counter
                        $a_def->files[substr($file, strlen(JPATH_ROOT))] += 1;
                    }
                    else
                    {
                        $a_def->files[substr($file, strlen(JPATH_ROOT))] = 1;
                    }
                    continue;
                }
            }//foreach
            if( ! $exists)
            {
                //-- new definition
                if($file != 'menu' && $file != 'submenu')
                {
                    $def->files=array(substr($file, strlen(JPATH_ROOT))=>1);
                }
                else
                {
                    $def->files = array($file);
                }
                $this->_definitions[] = $def;
            }
        }

    }//function

    function displayFields($lang, $file)
    {
        echo '<div style="background-color: #EEEEEE; padding: 10px;">';
        foreach ($file as $line)
        {
            if(strpos($line, '@version'))
            {
                echo '<div style="color: green;">'.$line.'</div>';
                continue;
            }
            echo htmlentities($line).'<br />';
        }//foreach
        echo '</div>';
    }//function

    /**
     * read a language file
     *
     * @param string $lang single language eg. 'en-GB'
     * @param string $path
     * @return mixed array of lines / false on error
     */
    private function _getFile($lang, $path, $core=false)
    {
        $fileName = $this->getFileName($lang, $this->_scope, $this->project, $core);
        if(JFile::exists($fileName))
        {
            //--Read the file
            $file = file($fileName);

            return $file;
        }
        else
        {
            //--FileNotFound
   #         ecrHTML::drawButtonCreateLanguageFile($lang, $this->_scope);

            return false;
        }
    }//function

    /**
     * creates a new file from request parameters
     *
     * @return bool true on success
     */
    function createFileFromRequest()
    {
        $ecr_project = JRequest::getCmd('ecr_project');
        $project = EasyProjectHelper::getProject($ecr_project);

        if( ! $project)
        {
            //--Something went wrong..
            JError::raiseWarning(100, JText::sprintf('Unable to load the project %s', $ecr_project));

            return false;
        }

        $scope = JRequest::getCmd('scope');
        $lang = JRequest::getVar('lngcreate_lang');

        $fileName = self::getFileName($lang, $scope, $project);

        $fileContents = '';
        $fileContents .= '# @version $Id'.'$'.NL;//Splitted to avoid property being setted
        $fileContents .= '# '.$ecr_project.' '.$scope.' language file'.NL;

        if( ! JFile::write($fileName, $fileContents))
        {
            return false;
        }

        return true;
    }//function

    /**
     * Output raw file as array
     *
     * @param array $file
     */
    function displayRaw($file)
    {
        echo '<pre style="background-color: #eeeeee; padding: 10px;">';
        foreach ($file as $line)
        {
            echo $line;
        }
        echo '</pre>';
    }//function

    /**
     * Generates a language file name.
     *
     * @param $lang string lang code eg. en-GB
     * @param $scope string eg. admin
     * @param $project object EasyProject
     * @return string full path to file
     */
    public function getFileName($lang, $scope, EasyProject $project, $core = false)
    {
        $fileName =($scope == 'admin' || $scope == 'menu') ? JPATH_ADMINISTRATOR : JPATH_SITE;
        $fileName .= DS.'language'.DS.$lang;

        if($core)
        {
            $fileName .= DS.$lang.'.ini';
        }
        else
        {
            $fileName .= DS.$lang.'.'.$project->getLanguageFileName($scope);
        }

        return $fileName;
    }//function

}//class
